/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package prototype;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author BuccatR
 */
public class MasterDownloader {

    /**
     * @param args the command line arguments
     */

    private String mainDirectory = "C:/";

    public static void main(String[] args) {
        MasterDownloader md = new MasterDownloader();
        String tag = "hatsune_miku";
        md.createDirectory(tag);
        md.downloadSankaku(tag);
    }

    private void createDirectory(String tag) {
        String newImageDirectory = this.mainDirectory + "/" + tag + "/";
        boolean createdDirectory = (new File(newImageDirectory)).mkdir();
        this.mainDirectory = newImageDirectory;
    }

    private void downloadSankaku(String tag) {
        ArrayList x = this.getImageURLS(getHTML("http://chan.sankakucomplex.com/?tags=" + tag + "&commit=Search"));
        for (Object y : x) {
            String targetURL = (String) y;
            System.out.println("[downloading] " + targetURL);
            this.download(targetURL);
        }
    }

    private ArrayList getImageURLS(String htmlString) {
        Pattern pattern = Pattern.compile("\\\"sample_url\\\":\\\".*?jpg\\\"");
        Matcher matcher = pattern.matcher(htmlString);
        ArrayList al = new ArrayList();
        while (matcher.find()) {
            String tempMatch = matcher.group();
            String temp1 = tempMatch.replace("\"sample_url\":\"", "");
            String temp2 = temp1.replace("\"","");
            al.add(temp2);
        }

        return al;
    }

    private String getHTML(String htmlURL) {
        try {
            StringBuffer outputHTML = new StringBuffer();
            URL targetURL = new URL(htmlURL);
            InputStreamReader inputStreamReader = new InputStreamReader(targetURL.openStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String htmlLine;

            while ((htmlLine = bufferedReader.readLine()) != null) {
                outputHTML.append(htmlLine);
            }

            return outputHTML.toString();

        } catch (MalformedURLException ex) {
            Logger.getLogger(MasterDownloader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MasterDownloader.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;

    }

    private void download(String URLPath) {
        try {
            URL targetURL = new URL(URLPath);
            BufferedInputStream bis = new BufferedInputStream(targetURL.openStream());

            String[] urlParts = targetURL.getFile().split("/");
            String fileName = urlParts[urlParts.length - 1];
            FileOutputStream fos = new FileOutputStream(this.mainDirectory + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

            byte[] data = new byte[1024];

            int x = 0;

            while ((x = bis.read(data,0,1024)) >= 0) {
                bos.write(data,0,x);
            }

            bos.close();
            bis.close();
            
        } catch (IOException ex) {
            Logger.getLogger(MasterDownloader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}